﻿using famails.bus;
using famails.dto;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.page
{

    public class DashboardResultJson
    {
        public string Title { get; set; }
        public decimal Value { get; set; }
        public double Percent { get; set; }
    }
    public partial class SendDashboard : System.Web.UI.Page
    {
        public decimal mailLimit = 10;
        public decimal countMail = 10;
        bool unlimit = false;
        public static decimal totalSent = 0;

        static UserLoginDTO userLogin = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            userLogin = getUserLogin();
            if (!IsPostBack)
            {
                //if (Request.QueryString["from"] + "" == "")
                //    txtFromDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                //else txtFromDate.Text = Request.QueryString["from"];
                //if (Request.QueryString["to"] + "" == "")
                //    txtToDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                //else txtToDate.Text = Request.QueryString["to"];

            }
            //DataTable table = new DataTable();

            CustomerBUS ctBUS = new CustomerBUS();
            //if (getUserLogin().DepartmentId == 2)
            //{
            //    table = ctBUS.GetClientId(getUserLogin().UserId);
            //}
            //else
            //{
            //    table = ctBUS.GetClientIdSub(getUserLogin().UserId);
            //}
            ////int clientid = Convert.ToInt32(table.Rows[0]["clientid"]);
            //if (table.Rows.Count > 0)
            //{
            //    int clienID = int.Parse(table.Rows[0]["clientId"].ToString());
            //    DataTable dtCountEmail = ctBUS.GetCountEmail(clienID);
            //    unlimit = Convert.ToBoolean(dtCountEmail.Rows[0]["isUnLimit"]);
            //    if (dtCountEmail.Rows[0]["isUnLimit"] + "" != "" && unlimit) mailLimit = 1000000000000000000;
            //    else mailLimit = decimal.Parse(dtCountEmail.Rows[0]["under"].ToString());
            //}

            //DataTable dtEmail = ctBUS.GetCountCustomerCreatedMail(getUserLogin().UserId);
            //countMail = decimal.Parse(dtEmail.Rows[0]["numberMail"].ToString());

            DataTable Table = ctBUS.Dashboard_EmailCount(userLogin.UserId);
            if (Table != null && Table.Rows.Count > 0)
            {
                decimal.TryParse(Table.Rows[0]["limit"] + "", out mailLimit);
                decimal.TryParse(Table.Rows[0]["mailcount"] + "", out countMail);
                lblPercent.Width = System.Web.UI.WebControls.Unit.Percentage((double)(countMail * 100 / mailLimit));
                lbltext.InnerText = (countMail * 100 / mailLimit).ToString("0.00") + "%(" + countMail.ToString("#,###") + "/" + mailLimit.ToString("#,###") + " email)";
            }
            if (!IsPostBack)
            {
                hdfUserID.Value = getUserLogin().UserId + "";
                pnlNguoiDung.Visible = getUserLogin().UserId == 1;
                UserLoginBUS user = new UserLoginBUS();
                DataTable T = user.GetAllUser();
                if (getUserLogin().UserId == 1)
                {
                    DataRow r = T.NewRow();
                    r["username"] = "Tất cả";
                    r["userid"] = 1;
                    T.Rows.InsertAt(r, 0);
                }
                ddlNguoiDung.DataSource = T;
                ddlNguoiDung.DataBind();

                ddlNguoiDung.Text = userLogin.UserId + "";
            }
        }

        public UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            else Response.Redirect("~/login.aspx?rUrl=" + Request.Url.PathAndQuery);
            return null;
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<DashboardResultJson> GetDashBoardData(string from, string to, int userid)
        {
            List<DashboardResultJson> result = new List<DashboardResultJson>();
            SendRegisterBUS bus = new SendRegisterBUS();
            userLogin = (UserLoginDTO)HttpContext.Current.Session["us-login"];
            DataTable T = bus.GetDashboadByTime(from, to, userLogin.UserId);
            if (T != null & T.Rows.Count > 0)
            {
                DashboardResultJson item = new DashboardResultJson();
                decimal temp = 0, total;
                decimal.TryParse(T.Rows[0]["TotalSend"] + "", out total);
                decimal.TryParse(T.Rows[0]["totalSent"] + "", out temp);
                double totalPer = 0;
                if (temp > 0)
                {
                    item.Value = temp;
                    double per = Math.Round((double)temp * 100 / (double)total, 2);
                    item.Percent = totalPer + per > 100 ? 100 - totalPer : per;
                    totalPer += item.Percent;
                    item.Title = "Tổng email gửi thành công: " + item.Value.ToString("#,###");
                    result.Add(item);
                }

                item = new DashboardResultJson(); temp = 0;
                decimal.TryParse(T.Rows[0]["totalBounce"] + "", out temp);
                if (temp > 0)
                {
                    item.Value = temp;
                    double per = Math.Round((double)temp * 100 / (double)total, 2);
                    item.Percent = totalPer + per > 100 ? 100 - totalPer : per;
                    totalPer += item.Percent;
                    item.Title = "Tổng email trả về: " + item.Value.ToString("#,###");
                    result.Add(item);
                }

                item = new DashboardResultJson(); temp = 0;
                decimal.TryParse(T.Rows[0]["totalNotSend"] + "", out temp);
                if (temp > 0)
                {
                    item.Value = temp;
                    double per = Math.Round((double)temp * 100 / (double)total, 2);
                    item.Percent = totalPer + per > 100 ? 100 - totalPer : per;
                    totalPer += item.Percent;
                    item.Title = "Tổng email chưa gửi: " + item.Value.ToString("#,###");
                    result.Add(item);
                }

                item = new DashboardResultJson(); temp = 0;
                decimal.TryParse(T.Rows[0]["totalSentErr"] + "", out temp);
                if (temp > 0)
                {
                    item.Value = temp;
                    double per = Math.Round((double)temp * 100 / (double)total, 2);
                    item.Percent = totalPer + per > 100 ? 100 - totalPer : per;
                    totalPer += item.Percent;
                    item.Title = "Tổng email lỗi: " + item.Value.ToString("#,###");
                    result.Add(item);
                }
            }
            return result;
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<DashboardResultJson> GetDashBoardResultData(string from, string to, int userid)
        {
            List<DashboardResultJson> result = new List<DashboardResultJson>();
            SendRegisterBUS bus = new SendRegisterBUS();
            userLogin = (UserLoginDTO)HttpContext.Current.Session["us-login"];
            DataTable T = bus.GetDashboadByTime(from, to, userLogin.UserId);
            if (T != null & T.Rows.Count > 0)
            {
                DashboardResultJson item = new DashboardResultJson();
                decimal open = 0, click = 0, sent, total;
                decimal.TryParse(T.Rows[0]["TotalSend"] + "", out totalSent);
                decimal.TryParse(T.Rows[0]["totalOpen"] + "", out open);
                double totalPer = 0;
                if (open > 0)
                {
                    item.Value = open;
                    //double per = Math.Round((double)open * 100 / (double)total, 2);
                    ////item.Percent = totalPer + per > 100 ? 100 - totalPer : per;
                    totalPer += item.Percent;
                    item.Title = "Tổng email mở: " + item.Value.ToString("#,###");
                    result.Add(item);
                }

                item = new DashboardResultJson(); click = 0;
                decimal.TryParse(T.Rows[0]["totalClick"] + "", out click);
                if (click > 0)
                {
                    item.Value = click;
                    //double per = Math.Round((double)click * 100 / (double)total, 2);
                    //item.Percent = totalPer + per > 100 ? 100 - totalPer : per;
                    totalPer += item.Percent;
                    item.Title = "Tổng email click: " + item.Value.ToString("#,###");
                    result.Add(item);
                }

                item = new DashboardResultJson(); sent = 0;
                decimal.TryParse(T.Rows[0]["totalSent"] + "", out sent);
                if (sent > 0)
                {
                    item.Value = sent - open;
                    //double per = Math.Round((double)(sent - open) * 100 / (double)total, 2);
                    //item.Percent = totalPer + per > 100 ? 100 - totalPer : per;
                    totalPer += item.Percent;
                    item.Title = "Tổng email chưa mở: " + item.Value.ToString("#,###");
                    result.Add(item);
                }
            }
            return result;
        }
    }
}